package cartagows;

import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cartago.ArtifactId;
import cartago.Op;
import cartago.OpFeedbackParam;
import cartago.util.agent.CartagoBasicContext;
 
public class Axis2Receiver implements MessageReceiver{
	private static final Log log = LogFactory.getLog(Axis2Receiver.class);
	private CartagoBasicContext ctx;
	synchronized public void receive(MessageContext messageCtx)
			throws AxisFault {
		//log.info("[AXIS2-RECEIVER] message arrived: " + messageCtx);
		//log.info("[AXIS2-RECEIVER] service: " + messageCtx.getAxisService().getName());
		//log.info("[AXIS2-RECEIVER] Header: " + messageCtx.getEnvelope().getHeader());
		//log.info("[AXIS2-RECEIVER] Body: " + messageCtx.getEnvelope().getBody().toString());

		MsgInfo msgContext = new MsgInfo(messageCtx);
		if (ctx == null) {

			try {
				//Join to the web-service workspace
				ctx = new CartagoBasicContext("axis2-receiver", CWSServiceManager.DEF_WSP_NAME);
				System.out.println("[Axis2Receiver] Join to workspace done, ready to receive messages.");
			}
			catch (Exception ex) {
				ex.printStackTrace();
				throw new AxisFault("service not found.");
			}
		}
		
		String addressTo = msgContext.getWSATo();
		if (addressTo != null) {
		
			int index = addressTo.lastIndexOf("/");
			String msgbox = addressTo.substring(index + 1);

			OpFeedbackParam<ArtifactId> aid = new OpFeedbackParam<ArtifactId>();
			try {
				//Lookup of the required WSPanel
				ctx.doAction(new Op("lookupArtifact", msgbox, aid), 300);
			} catch (Exception ex) {
				ex.printStackTrace();
				throw new AxisFault("Artifact "+msgbox+" not found: service or endpoint not available.");
			}
			//New message notification
			try {
				ctx.doAction(aid.get(), new Op("notifyMsg", msgContext), 300);
			} catch (Exception ex) {
				System.out.println(msgContext.toString());
				ex.printStackTrace();
				throw new AxisFault("Error in artifact interaction.");
			}
		} else {
			throw new AxisFault("Unknown EPR.");
		}
	}
}